package org.iabako.server.serviceimpl.security;

import org.apache.log4j.Logger;
import org.iabako.server.dao.user.EnterpriseDAO;
import org.iabako.shared.entity.user.Enterprise;
import org.iabako.shared.entity.user.User;
import org.iabako.shared.iservice.business.CustomFieldService;
import org.iabako.shared.iservice.security.AuthenticateService;
import org.iabako.shared.iservice.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * Created by jose on 24/09/14.
 */

@Service("authenticateService")
public class AuthenticateServiceImpl implements AuthenticateService {

    static Logger log = Logger.getLogger(AuthenticateServiceImpl.class.getName());

    @Autowired
    UserService userService;
    @Autowired
    EnterpriseDAO enterpriseDAO;
    @Autowired
    SpringUserDetailsService springUserDetailsService;
    @Autowired
    CustomFieldService customFieldService;

    @Autowired
    SessionUser sessionUser;

    public User getAuthenticatedUser() {
        if (sessionUser.getUser() == null) {
            reloadAuthenticatedUser();
        }

        return sessionUser.getUser();
    }

    public User reloadAuthenticatedUser() {
        User user = null;
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            user = userService.getUserByEmail(((UserDetails) principal).getUsername());
            user.getEnterprise().setChildrenEnterprises(enterpriseDAO.getChildrenEnterprises(user.getEnterprise()));
            user.getEnterprise().setAllRelatedEnterprise(enterpriseDAO.getAllRelatedEnterprises(user.getEnterprise()));
            user.getEnterprise().setUsersNumber(enterpriseDAO.getUsersNumber(user.getEnterprise()));
            user.getEnterprise().setPrincipalUser(enterpriseDAO.getPrincipalUser(user.getEnterprise()));
            sessionUser.setUser(user);
            //This must be after the setUser in session
            user.getEnterprise().setCustomFields(customFieldService.getCustomFields());
        }

        return user;
    }

    /**
     * This method is used only as a PayPal workflow workaround. It is called by a manual IU link
     * (ex. automatic redirection not working and User come back to IABAKO)
     *
     * @return
     */
    public User reloadEnterpriseCredit() {
        try {
            springUserDetailsService.verifyNotIntegratedPayments(sessionUser.getUser().getEnterprise());
            sessionUser.getUser().setGoToPayPal(false);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return reloadAuthenticatedUser();
    }

    public Enterprise getParentEnterprise() {
        return sessionUser.getUser().getEnterprise().getParentEnterprise();
    }
}
